package com.manage.utils;

import java.io.File;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;

import com.manage.activity.ShareSinaWeiboActivity;

import weibo4andriod.Status;
import weibo4andriod.Weibo;
import weibo4andriod.WeiboException;
import weibo4andriod.http.ImageItem;
import weibo4andriod.http.RequestToken;
import android.app.Activity;
import android.app.Dialog;
import android.app.ProgressDialog;
import android.content.Intent;
import android.content.SharedPreferences;
import android.net.Uri;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.util.Log;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.Button;


public class SinaWeiboPoster {

	private static String rs1, rs2;
	private static String photoPath;
	private static ProgressDialog progressDialog;
	private static String RESULT = "result";
	private static Activity context;
	public static String result;
	private List<WeiboListener> listeners = new ArrayList<WeiboListener>();
	public static final String RESULT_OK = "Ok";
	public static final String RESULT_FAILED = "failed";

	public void setWeiboListener(WeiboListener listener) {
		this.listeners.add(listener);
	}

	public void removeWeiboListener(WeiboListener listener) {
		this.listeners.remove(listener);
	}

	public void postBlogOAuth(Activity activity) {
		Weibo.CONSUMER_KEY = "3185608097";
		Weibo.CONSUMER_SECRET = "95a885949d1e74b3c7d0ae9917fdaa88";
		context = activity;
		SharedPreferences spf = activity.getSharedPreferences("data", Activity.MODE_PRIVATE);
		if (spf != null) {
			rs1 = spf.getString("Tocken", null);
			rs2 = spf.getString("TokenSecret", null);
		}
//		photoPath = activity.getFilesDir() + File.separator + AppConstans.TEMP_PHOTO_FILE;
		if (rs1 != null && rs2 != null) {
			gotoShareSinaWeiboActivity();
			return;
		}
		System.setProperty("weibo4j.oauth.consumerKey", Weibo.CONSUMER_KEY);
		System.setProperty("weibo4j.oauth.consumerSecret", Weibo.CONSUMER_SECRET);
		showOAuthDialog();

	}

	private void showOAuthDialog() {
		// TODO Auto-generated method stub
//		View diaView = View.inflate(context, R.layout.sinaweibo_oauth_dialog, null);
//		final Dialog dialog = new Dialog(context, R.style.weibo_oauth_dialog);
//		dialog.setContentView(diaView);
//		dialog.show();

//		Button stratBtn = (Button) diaView.findViewById(R.id.btn_oauth_weibo);

//		stratBtn.setOnClickListener(new OnClickListener() {

//			@Override
//			public void onClick(View v) {
//				Weibo weibo = OAuthConstant.getInstance().getWeibo(true);
//				RequestToken requestToken;
//				try {
//					requestToken = weibo.getOAuthRequestToken("maidong://ShareSinaWeiboActivity");
//					Uri uri = Uri.parse(requestToken.getAuthenticationURL() + "&from=xweibo");
//					OAuthConstant.getInstance().setRequestToken(requestToken);
//					context.startActivity(new Intent(Intent.ACTION_VIEW, uri).addFlags(Intent.FLAG_ACTIVITY_NO_HISTORY));
//					dialog.dismiss();
//				} catch (WeiboException e) {
//					AppUtils.logE(e);
//				}
//
//			}
//		});

	}

	private void gotoShareSinaWeiboActivity() {
		// TODO Auto-generated method stub
		Intent intent = new Intent();
		intent.addFlags(Intent.FLAG_ACTIVITY_NO_HISTORY);
		intent.setClass(context, ShareSinaWeiboActivity.class);
		context.startActivity(intent);
	}

	public void postPhotoUpload(Activity activity) {
		progressDialog = ProgressDialog.show(activity, "上传中", "上传中，请稍等……");
		progressDialog.show();
		context = activity;
		new Thread(new PostPhotoUploadRunnable()).start();
	}

	private class PostPhotoUploadRunnable implements Runnable {

		public void run() {
			Bundle data = new Bundle();
			Message msg = new Message();
			rs1 = context.getSharedPreferences("data", Activity.MODE_PRIVATE).getString("Tocken", null);
			rs2 = context.getSharedPreferences("data", Activity.MODE_PRIVATE).getString("TokenSecret", null);
			String[] upString = { rs1, rs2, photoPath, "Bug管理系统" };
			Date reg = uploadImage(upString);
			if (reg != null) {
				data.putString(RESULT, RESULT_OK);
			} else {
				data.putString(RESULT, RESULT_FAILED);
			}

			msg.setData(data);
			handler.sendMessage(msg);

		}
	}

	private Handler handler = new Handler() {

		@Override
		public void handleMessage(Message msg) {
			// TODO Auto-generated method stub
			super.handleMessage(msg);
			progressDialog.dismiss();
			for (WeiboListener w : listeners) {
				w.afterPost(msg.getData().getString(RESULT));
			}
		}

	};

	private Date uploadImage(String args[]) {
		try {

			System.setProperty("weibo4j.oauth.consumerKey", Weibo.CONSUMER_KEY);
			System.setProperty("weibo4j.oauth.consumerSecret", Weibo.CONSUMER_SECRET);
			Weibo weibo = OAuthConstant.getInstance().getWeibo(false);
			weibo.setToken(args[0], args[1]);

			try {
				byte[] content = AppUtils.readFile(args[2]);
				Log.e("+++", "content length:" + content.length);
				ImageItem pic = new ImageItem("pic", content);
				String url1 = java.net.URLEncoder.encode(args[3], "UTF-8");
				Log.e("@+@", url1);
				Status status = weibo.uploadStatus(url1, pic);
				Log.e("@++", "Successfully upload the status to [" + status.getText() + "].");
				Date result = status.getCreatedAt();
				return result;
			} catch (Exception e1) {
				e1.printStackTrace();
			}
		} catch (Exception ioe) {
			Log.e("@++", "Failed to read the system input.");
		}
		return null;
	}

	public interface WeiboListener {
		public void afterPost(String result);
	}
}
